package com.vogue.sms.controller;


import com.vogue.sms.annotation.Login;
import com.vogue.sms.common.utils.R;
import com.vogue.sms.common.validator.ValidatorUtils;
import com.vogue.sms.entity.ApiUserEntity;
import com.vogue.sms.form.LoginForm;
import com.vogue.sms.form.RegisterForm;
import com.vogue.sms.service.ApiTokenService;
import com.vogue.sms.service.ApiUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Date;
import java.util.Map;

/**
 * 登录接口
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-03-23 15:31
 */
@RestController
@RequestMapping("/api")
@Api(tags="登录接口")
public class ApiUserController {
    @Autowired
    private ApiUserService userService;
    @Autowired
    private ApiTokenService tokenService;

    @PostMapping("register")
    @ApiOperation("注册")
    public R register(@RequestBody RegisterForm form){
        //表单校验
        ValidatorUtils.validateEntity(form);

        ApiUserEntity user = new ApiUserEntity();
        user.setMobile(form.getMobile());
        user.setUsername(form.getMobile());
        user.setPassword(DigestUtils.sha256Hex(form.getPassword()));
        user.setCreateTime(new Date());
        userService.insert(user);

        return R.ok();
    }

    @PostMapping("login")
    @ApiOperation("登录")
    public R login(@RequestParam String mobile,@RequestParam String password ){
        LoginForm form=new LoginForm();
        form.setMobile(mobile);
        form.setPassword(password);
        //用户登录
        Map<String, Object> map = userService.login(form);

        return R.ok(map);
    }

    @Login
    @PostMapping("logout")
    @ApiOperation("退出")
    public R logout(@ApiIgnore @RequestAttribute("userId") long userId){
        tokenService.expireToken(userId);
        return R.ok();
    }

}
